package com.webproject.shop.controller;

import com.webproject.shop.common.BusinessException;
import com.webproject.shop.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.webproject.shop.common.ResponseModel;
import com.webproject.shop.pojo.Cart;
import com.webproject.shop.service.CartService;
import com.webproject.shop.common.ErrorCode;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/cart")
@CrossOrigin(origins = "${webproject.web.path}", allowedHeaders = "*", allowCredentials = "true")
public class CartController implements ErrorCode{
    @Autowired
    private CartService cartService;

    //前端获取当前登录用户的购物车清单
    @RequestMapping(path = "/cartlist", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel getUserCart(String username){
        List<Cart> carts = cartService.selectCartByUserName(username);
        return new ResponseModel(carts);
    }

    //添加购物车，需要前端传入商品id和数量
    @RequestMapping(path = "/addproduct", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel addProduct(Cart cart){
        cartService.insertCart(cart);
        return new ResponseModel(cart);
    }

    //删除购物车中的商品，需要前端传入当前登陆的用户名，商品id
    @RequestMapping(path = "/deleteproduct", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel deleteProduct(Cart cart){
        cartService.deleteCart(cart);
        return new ResponseModel(cart);
    }

    //更新购物车中信息，如在购物车页面中
    @RequestMapping(path = "/updatecart", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel updateCart(Cart cart){
        cartService.updateCart(cart);
        return new ResponseModel(cart);
    }

    //购物车结算
    @RequestMapping(path = "/createOrder", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel createOrder(HttpSession httpSession,String username){
        User user = (User) httpSession.getAttribute("loginUser");
        if(user == null)
            throw new BusinessException(USER_NOT_LOGIN, "未登录!");
        cartService.createOrder(username);
        return new ResponseModel();
    }



}
